package courses;

import javax.swing.*;

public class Moving {
    JFrame jf;
    JLabel label;

    class MyThread extends Thread {
        @Override
        public void run() {
            int d = 0, i = 1;
            boolean rEdge = false;
            super.run();
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                label.setBounds(20 + d * i, 300, 200, 50);
                if (rEdge == false) {
                    i++;
                    if (i >= 20) {
                        rEdge = true;
                    } else {
                        rEdge = false;
                    }
                } else {
                    i--;
                }

            }
        }
    }

    public Moving() {
        jf = new JFrame("多线程实现动画效果");
        label = new JLabel("我飘过去了");
    }

    public void init() {
        jf.setLayout(null);
        label.setBounds(20, 300, 200, 50);
        jf.add(label);
        jf.setVisible(true);
        jf.setSize(500, 500);

        // 创建一个线程并启动
        new MyThread().start();
    }

    public static void main(String[] args) {
        new Moving().init();
    }
}
